package com.hongawen.poi.service;

import cn.afterturn.easypoi.cache.manager.FileLoaderImpl;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.CharsetUtil;
import com.hongawen.poi.pojo.Company;
import com.hongawen.poi.pojo.Student;
import com.hongawen.poi.util.HttpServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2022年03月31日 14:18
 */
@Slf4j
@Component
public class ImageService {

    private static List<Company> companies = new ArrayList<>();

    static {
        Company company = new Company();
        company.setName("百度");

        try {
            company.setCompanyLogo(IOUtils.toByteArray(FileLoaderImpl.class.getClassLoader().getResourceAsStream("static/imgs/baidu.png")));
            companies.add(company);
        } catch (IOException e) {
            e.printStackTrace();
        }


        company = new Company();
        company.setName("灿能");
        try {
            company.setCompanyLogo(IOUtils.toByteArray(FileLoaderImpl.class.getClassLoader().getResourceAsStream("static/imgs/logo.png")));
            companies.add(company);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void exportCompany() {
        try {
            HttpServletResponse response = HttpServletUtil.getResponse();
            String fileName = URLEncoder.encode("hello.xls", CharsetUtil.UTF_8);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            ServletOutputStream outputStream = response.getOutputStream();
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Company.class, companies);
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            log.error(">>> 导出数据异常：{}", e.getMessage());
        }
    }



}
